package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.BorrowRecordMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.BorrowRecord;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.pojo.vo.BorrowRecordVo;
import com.itheima.service.BorrowRecordService;
import com.itheima.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Mapper;
import org.assertj.core.error.ShouldHaveSizeGreaterThan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class BorrowRecordServiceImpl  implements BorrowRecordService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BorrowRecordMapper borrowRecordMapper;
    @Override
    public PageBean<BorrowRecordVo> list(Integer pageNum, Integer pageSize, String cardNumber, Integer bookId, Integer status) {
        PageBean<BorrowRecordVo> pageBean=new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);
        List<BorrowRecordVo> list = borrowRecordMapper.list(cardNumber, bookId, status);
        Page<BorrowRecordVo> page=(Page<BorrowRecordVo>)list;
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    @Override
    public void add(BorrowRecord borrowRecord) {
        String cardNumber = borrowRecord.getCardNumber();
        User user = userMapper.getByCardNumber(cardNumber);
        if(user==null){
            throw new BusinessException("该卡号不存在");
        }
        borrowRecord.setStatus(0);
        borrowRecord.setUserId(user.getId());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer operatorId = (Integer) map.get("id");
        borrowRecord.setOperatorId(operatorId);
        borrowRecord.setBorrowTime(LocalDateTime.now());
        borrowRecord.setExpectedReturnTime(LocalDateTime.now().plusDays(15));
        borrowRecordMapper.add(borrowRecord);
    }

    @Override
    public void update(BorrowRecord borrowRecord) {
        Map<String,Object> map = ThreadLocalUtil.get();
        User operator = (User)map.get("id");
        borrowRecord.setOperatorId(operator.getId());
        borrowRecordMapper.update(borrowRecord);
    }

    @Override
    public void delete(Integer id) {
        borrowRecordMapper.delete(id);
    }

    @Override
    public void updateStatus(Integer id) {
        borrowRecordMapper.updateStatus(id);
    }
}
